package com.zhidian.edm.service.impl;

import com.zhidian.edm.service.AuthInfoService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AuthInfoServiceImpl implements AuthInfoService {

    @Override
    public Map<String, Object> getInfoByUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Map<String, Object> resultMap = new HashMap<>();
        if (authentication == null) {
            // 未认证时返回空Map
            return resultMap;
        }
        Object principal = authentication.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = null;
        if (principal instanceof UserDetails) {
            // 从UserDetails中获取权限
            authorities = ((UserDetails) principal).getAuthorities();
        } else if (principal instanceof Authentication) {
            // 特殊情况：principal本身是Authentication对象
            authorities = ((Authentication) principal).getAuthorities();
        }

        if (authorities != null) {
            // 分离权限和角色（角色以ROLE_为前缀）
            List<String> perms = new ArrayList<>();
            List<String> roles = new ArrayList<>();

            for (GrantedAuthority authority : authorities) {
                String authorityStr = authority.getAuthority();
                // 假设权限包含冒号（如user:list），
                if (authorityStr.contains(":")) {
                    perms.add(authorityStr); // 权限
                } else {
                    roles.add(authorityStr); // 角色（已无ROLE_前缀）
                }
            }

            resultMap.put("perms", perms);
            resultMap.put("roles", roles);
        } else {
            // 无权限信息时返回空列表
            resultMap.put("perms", Collections.emptyList());
            resultMap.put("roles", Collections.emptyList());
        }

        return resultMap;

    }
}
